const router = require('koa-router')()
const ProjectSchema = require('../model/projectSchema')
const utils = require('../utils/utils')
const uuid = require('node-uuid')
const dayjs = require('dayjs')
const today = dayjs().format('YYYY-MM-DD')
router.prefix('/project')
router.get('/list', async (ctx) => {
  try {
    const res = await ProjectSchema.find({ state: 1 })
    if (res) {
      ctx.body = utils.success(res)
    } else {
      ctx.body = utils.fail('数据检索异常')
    }
  } catch (error) {
    ctx.body = utils.fail(error.msg)
  }
})

router.post('/addProject', async (ctx) => {
  try {
    const {
      name,
      repostory,
      type,
      userId,
      deptId,
      feId,
      feName,
      backendName,
      pm,
      projectDesc,
      businessId,
      testInfo,
      prodInfo,
      remark,
      state
    } = ctx.request.body
    const project = await new ProjectSchema({
      id: uuid.v4(),
      name,
      repostory,
      type,
      userId,
      deptId,
      feId,
      feName,
      createTime: today,
      backendName,
      pm,
      projectDesc,
      businessId,
      testInfo,
      prodInfo,
      remark,
      state
    })
    await project.save((err, data) => {
      if (err) {
        ctx.body = utils.fail(err.msg)
      }
    })
    ctx.body = utils.success({}, '添加成功')
  } catch (error) {
    ctx.body = utils.fail(error.msg)
  }
})

router.post('/editProject', async (ctx) => {
  console.log('参数', ctx.request.body)
  // 修改数据
  // 检索数据
  const {
    _id,
    name,
    repostory,
    type,
    userId,
    deptId,
    feId,
    feName,
    backendName,
    pm,
    projectDesc,
    businessId,
    testInfo,
    prodInfo,
    remark,
    state
  } = ctx.request.body
  console.log('有没有id', _id)
  ProjectSchema.findByIdAndUpdate(
    _id,
    {
      name,
      repostory,
      type,
      userId,
      deptId,
      feId,
      feName,
      backendName,
      pm,
      projectDesc,
      businessId,
      testInfo,
      prodInfo,
      remark,
      state
    },
    (err, doc) => {
      if (err) {
        ctx.body = utils.fail(err.msg)
      }
    }
  )
  ctx.body = utils.success({}, '修改成功')
})

module.exports = router
